<template>
  <view>
    <view class="container">
      <view class='edit-container'>
        <view class="a-item">
          <view class="icon">
            <image class="img" src="/static/images/icon/receiver.png"></image>
          </view>
          <view class="input-wrap">
            <input cursor-spacing='100' v-model="formData.name" class='a-input' placeholder='姓名'></input>
          </view>
        </view>
        <view class="a-item">
          <view class="icon">
            <image class="img" src="/static/images/icon/mobile.png"></image>
          </view>
          <view class="input-wrap">
            <input cursor-spacing='100' class='a-input' v-model="formData.mobile" type='number'
              placeholder='手机号码'></input>
          </view>
        </view>
        <view class="a-item">
          <view class="icon">
            <image class="img" src="/static/images/icon/position.png"></image>
          </view>
          <view class="input-wrap">
            <input cursor-spacing='100' @click="chooseRegion" class="a-input" :value="full_region" disabled="true"
              placeholder="选择省份、城市、区县" />
            <view class="arrow"></view>
          </view>
        </view>
        <view class="a-item">
          <view class="icon">
            <image class="img" src="/static/images/icon/address.png"></image>
          </view>
          <view class="input-wrap">
            <input cursor-spacing='100' v-model ='formData.address' class="a-input" placeholder="详细地址, 如街道、小区或写字楼等" />
          </view>
        </view>
      </view>
      <view class="default-wrap">
        <view class="text">设为默认地址</view>
        <!--这里用的 uview组件库的开关-->
        <u-switch v-model="formData.is_default" :activeValue="1" :inactiveValue="0" class="switch"></u-switch>
      </view>
      <view class='btn-wrap'>
        <view class="btn active" @click='saveAddress'>保存</view>
      </view>
      <view class='delete-wrap'>
  				<view class='btn' @click="delAddress">删除</view>
  			</view>
      <view class="region-select" v-if="regionShow">
        <view class="hd">
          <view class="region-selected">
            <!-- 选中的渲染 -->
            <view class="item" v-for="(item,index) in selectRegionList" :key="index"
              @click="selectRegionType(item,index)" :class="{disabled: item.id===0,selected: regionType===index+1}">
              {{item.name}}</view>
          </view>
          <view class="done" :class="{ disabled:confirmDisabled }" @click="doneSelectRegion">确定</view>
        </view>
        <view class="bd">
          <scroll-view scroll-y class="region-list">
            <!-- 省市区的列表渲染 -->
            <view class="item" :class="{selected:item.selected}" v-for="item in regionList" :key="item.id"
              @click="selectRegion(item)">{{item.name}}</view>
          </scroll-view>
        </view>
      </view>
    </view>
    <view class="bg-mask" @click="cancelSelectRegion" v-if="regionShow"></view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        regionShow: false, //省市区展示
        formData: {
          name: '', // 姓名
          mobile: '', // 手机号
          address: '', // 详细地址信息
          province_id: '', // 省份ID
          city_id: '', // 城市ID
          district_id: '', // 区县ID
          is_default: 0 // 是否默认
        },
        selectRegionList: [ // 用于渲染顶部位置信息
          {
            id: 0,
            name: '省份',
            parent_id: 1,
            type: 1
          },
          {
            id: 0,
            name: '城市',
            parent_id: 1,
            type: 2
          },
          {
            id: 0,
            name: '区县',
            parent_id: 1,
            type: 3
          }
        ],
        regionType: 1, // 1选择省份， 2选择城市， 3选择区县
        regionList: [], // 地址列表
        addressInfo: { // 记录省市县名称
          province_name: '',
          city_name: '',
          district_name: ''
        },
        addressId:""
      };
    },
    onLoad(options) {
        // 如果携带了id，说明是修改界面
        if(options.id){
            // 存储地址
            this.addressId = options.id
            // 修改标题
            uni.setNavigationBarTitle({
                title:'修改地址'
            })
            // 获取回显数据
            this.getAddressInfo()
        }
    },
    methods: {
       // 删除地址
          async delAddress(){
              // 弹出确认框
              let res = await  uni.showModal({
                  content:'确认删除吗？'
              })
              if(res.cancel) return
              // 发生删除请求
              await uni.$http.post('/address/deleteAddress',{ id:this.addressId })
              // 提示成功
              uni.showToast({
                  title:'删除成功',
                  duration:300
              })
              setTimeout(()=>{
                  uni.navigateBack()
              },300)
          },
       // 修改获取回显数据
          async getAddressInfo(){
              let res = await uni.$http.get('/address/addressDetail',{ params:{ id:this.addressId } })
              this.formData = res
              this.addressInfo.province_name = res.province_name
              this.addressInfo.city_name = res.city_name
              this.addressInfo.district_name = res.district_name
          },
      // 点击完成按钮
      doneSelectRegion() {
        // 如果按钮禁用
        if (this.confirmDisabled) return
        // 将selectRegionList里面数据保存到formData
        this.formData.province_id = this.selectRegionList[0].id,
          this.formData.city_id = this.selectRegionList[1].id
        this.formData.district_id = this.selectRegionList[2].id
        // 收集选择对应的地区名称
        this.addressInfo.province_name = this.selectRegionList[0].name
        this.addressInfo.city_name = this.selectRegionList[1].name
        this.addressInfo.district_name = this.selectRegionList[2].name
        // 关闭弹框
        this.regionShow = false
      },
      //点击弹出选择省市县
      chooseRegion() {
        this.regionShow = true
        // 是否有选择过
        if (this.formData.province_id > 0 && this.formData.city_id > 0 && this.formData.district_id > 0) {
          // 	设置区域选择数据	
          this.selectRegionList[0].id = this.formData.province_id
          this.selectRegionList[0].name = this.addressInfo.province_name
          this.selectRegionList[0].parent_id = 1
          this.selectRegionList[1].id = this.formData.city_id
          this.selectRegionList[1].name = this.addressInfo.city_name
          this.selectRegionList[1].parent_id = this.formData.province_id
          this.selectRegionList[2].id = this.formData.district_id
          this.selectRegionList[2].name = this.addressInfo.district_name
          this.selectRegionList[2].parent_id = this.formData.city_id
          // 设置类型为3级
          this.regionType = 3
          // 取3级的数据
          this.getRegionList(this.formData.city_id)
        } else {
          // 情况1：从未选择过但打开了(第一次)   情况2：之前选择过，点击去了取消(注意了selectRegionList可能有残留数据)
          this.selectRegionList = [{
                id: 0,
                name: '省份',
                parent_id: 1,
                type: 1
              },
              {
                id: 0,
                name: '城市',
                parent_id: 1,
                type: 2
              },
              {
                id: 0,
                name: '区县',
                parent_id: 1,
                type: 3
              }
            ],
            // 设置类型为1级
            this.regionType = 1
          this.getRegionList(1)
        }
      },
      // 取消地区选择
      cancelSelectRegion() {
        this.regionShow = false
        this.regionType = this.confirmDisabled ? 1 : 3
      },
      async getRegionList(regionId) {
        //得到的是35个省
        const res = await uni.$http.get('/region/list', {
          params: {
            parentId: regionId
          }
        })
        console.log(res, 'res')
        //标记已经选择
        this.regionList = res.map(item => {
          if (this.regionType === item.type && this.selectRegionList[this.regionType - 1].id === item.id) {
            item.selected = true
          } else {
            item.selected = false
          }
          return item
        })
      },
      selectRegion(val) {
        console.log(val)
        // 更新顶部对应变量
        this.selectRegionList.splice(val.type - 1, 1, val)
        //更新类型，获取下拉列表
        if (this.regionType !== 3) {
          this.regionType++
          this.getRegionList(val.id)
        }
        // 重置下级区域为空[新增]
        this.selectRegionList = this.selectRegionList.map((item, index) => {
          if (index > val.type - 1) {
            item.id = 0
            item.name = index === 1 ? "城市" : '区县'
            item.parent_id = 1
          }
          return item
        })


        this.regionList = this.regionList.map(item => {
          if (this.regionType === item.type && this.selectRegionList[this.regionType - 1].id === item.id) {
            item.selected = true
          } else {
            item.selected = false
          }
          return item
        })
      },
      //  区域被点击
      selectRegionType(val, idx) {
        // 如果对应的id为0，说明还没有选择，就不要切换点击，跳出
        // 如果当前是高亮，点击也没有意义
        // 1.高亮不让点击,禁用不让点击
        // idx只能可能是0,1,2 this.selectRegionList[idx]
        if (val.type === this.regionType) return //高亮
        if (this.selectRegionList[idx].id === 0) return //禁用
        // val 就是头部点击的信息，选择的省市县里面的某一个的详细选中信息
        this.regionType = idx + 1 //高亮
        // 获取地址的列表
        this.getRegionList(val.parent_id) //列表更新
      },
      // 保存地址
      async saveAddress() {
        // 1. 数据的校验,不做细致的校验，只做空置的校验
        let valueArr = Object.values(this.formData)
        if (valueArr.some(item => item === '')) return uni.showToast({
          title: '有数据没填写',
          icon: 'error'
        })
        // 2. 发起请求
        await uni.$http.post('/address/saveAddress', this.formData)
        // 判断是否有Id,如果有就是编辑
           uni.showToast({
                    title: this.addressId ? '修改成功' : '添加成功',
                    icon:'success'
                })
        // // 3. 提示成功
        // uni.showToast({
        //   title: '添加成功',
        //   icon: 'success',
        //   duration: 300
        // })
        // 4.跳转
        setTimeout(() => {
          uni.navigateBack()
        }, 300)
      }
    },
    computed: {
      confirmDisabled() {
        return this.selectRegionList.some(item => item.id === 0)
      },
      // 其他。。。
      // 地区名称完整描述
      full_region() {
        return Object.values(this.addressInfo).join('')
      }
    }
  }
</script>

<style lang="scss">
  page {
    min-height: 100%;
    background-color: #f8f8f8;
  }

  .container {
    min-height: 100%;
    /* align-items: stretch; */
    background: #f8f8f8;
    overflow-x: hidden;
    padding: 30rpx;
  }

  .edit-container {
    background: #fff;
    width: 100%;
    margin-bottom: 30rpx;
    border-radius: 10rpx;
    box-shadow: 2rpx 8rpx 18rpx #f1f1f1;
  }

  .a-item {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-left: 30rpx;
  }

  .a-item .icon {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-right: 20rpx;
  }

  .a-item .icon .img {
    width: 36rpx;
    height: 36rpx;
  }

  .a-item .input-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 30rpx 30rpx 30rpx 0;
    border-bottom: 1rpx solid #f1f1f1;
  }

  .a-item:last-child .input-wrap {
    border-bottom: none;
  }

  .a-item .input-wrap .a-input {
    font-size: 28rpx;
    width: 100%;
  }

  .a-item .input-wrap .arrow {
    width: 10rpx;
    height: 10rpx;
    border-top: 4rpx solid #aaa;
    border-right: 4rpx solid #aaa;
    transform: rotate(45deg);
  }

  .a-input {
    font-size: 28rpx;
    width: 100%;
  }

  .confirm-box {
    width: 100%;
    height: 100rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    /* border-top:1px solid #eee;  */
    background: linear-gradient(to right, #ff116a, #fe5b46);
    text-align: center;
    line-height: 100rpx;
    color: #fff;
    font-size: 32rpx;
  }

  .default-input {
    font-size: 28rpx;
    color: #233445;
    line-height: 60rpx;
    margin: 0 auto;
    width: 300rpx;
  }

  .region-select {
    width: 100%;
    height: 600rpx;
    background: #fff;
    position: fixed;
    z-index: 10;
    left: 0;
    bottom: 0;
  }

  .region-select .hd {
    height: 108rpx;
    width: 100%;
    border-bottom: 1px solid #f4f4f4;
    padding: 46rpx 30rpx 0 30rpx;
    box-sizing: border-box;
  }

  .region-select .region-selected {
    float: left;
    height: 60rpx;
    display: flex;
  }

  .region-select .region-selected .item {
    max-width: 140rpx;
    margin-right: 30rpx;
    text-align: left;
    line-height: 60rpx;
    height: 100%;
    color: #333;
    font-size: 28rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .region-select .region-selected .item.disabled {
    color: #999;
  }

  .region-select .region-selected .item.selected {
    color: #ff3456;
  }

  .region-select .done {
    float: right;
    height: 60rpx;
    width: 60rpx;
    border: none;
    background: #fff;
    line-height: 60rpx;
    text-align: center;
    color: #ff3456;
    font-size: 28rpx;
  }

  .region-select .done.disabled {
    color: #999;
  }

  .region-select .bd {
    height: 492rpx;
    width: 100%;
    padding: 0 30rpx;
  }

  .region-select .region-list {
    height: 492rpx;
  }

  .region-select .region-list .item {
    width: 100%;
    height: 104rpx;
    line-height: 104rpx;
    text-align: left;
    color: #333;
    font-size: 28rpx;
  }

  .region-select .region-list .item.selected {
    color: #ff3456;
  }

  .bg-mask {
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.4);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 8;
  }

  .default-wrap {
    background: #fff;
    width: 100%;
    margin-bottom: 30rpx;
    border-radius: 10rpx;
    box-shadow: 2rpx 8rpx 18rpx #f1f1f1;
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
  }

  .default-wrap .text {
    font-size: 28rpx;
  }

  .btn-wrap {
    width: 100%;
    padding: 24rpx 0;
    /* position: fixed;
    bottom: 0;
    left: 0; */
    box-sizing: border-box;
  }

  .btn-wrap .btn {
    font-size: 28rpx;
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    border-radius: 10rpx;
    width: 100%;
    color: #fff;
    background: #bbb;
    box-shadow: 0rpx 10rpx 20rpx #ccc;
  }

  .btn-wrap .btn.active {
    background: linear-gradient(to right, #ff3456, #ff347d);
    box-shadow: 0rpx 10rpx 20rpx #f1f1f1;
    color: #fff;
  }

  .delete-wrap {
    width: 100%;
    padding: 24rpx;
    /* position: fixed;
    bottom: 0;
    left: 0; */
    box-sizing: border-box;
  }

  .delete-wrap .btn {
    font-size: 28rpx;
    color: #5d6777;
    text-align: center;
  }
</style>
